package com.taobao.classloader.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.util.ResourceUtils;

import com.taobao.classloader.ApplicationContextCreator;
import com.taobao.classloader.ClassLoaderScope;

public class AllocateClassLoaderContextCreator extends ApplicationObjectSupport implements ApplicationContextCreator {
	String	CLASSPATH_URL_PREFIX	= ResourceUtils.CLASSPATH_URL_PREFIX;

	public ApplicationContext createApplicationContext(ClassLoaderScope scope, ClassLoader classLoader) {
		ApplicationContext context = null;
		if (scope instanceof SpringClassLoaderScope) {
			SpringClassLoaderScope springScope = (SpringClassLoaderScope) scope;
			String[] paths = springScope.getContextConfigPaths();
			context = null;
			ApplicationContext parent = getApplicationContext();
			if (paths != null && paths.length > 0) {
				if (paths[0].startsWith(CLASSPATH_URL_PREFIX)) {
					context = new ClassPathXmlApplicationContext(paths,false, parent);
				} else {
					context = new FileSystemXmlApplicationContext(paths,false, parent);
				}
				((DefaultResourceLoader) context).setClassLoader(classLoader);
			} else {
				context = parent;
			}
		} else {
			context = getApplicationContext();
		}

		return context;
	}
}
